package vip.zhenzicheng.algorithm;

/**
 * 位运算
 *
 * @author zhenzicheng
 * @date 2022-06-10 13:12
 */
public class BitOperation {

  public static void main(String[] args) {
    int a = 10;
    int b = 20;
    swap(a, b);
  }

  public static void swap(int a, int b) {
    // 使用临时变量
    int temp = a;
    a = b;
    b = temp;

    // 使用相加再相减
    a = a + b;
    b = a - b;
    a = a - b;

    // 使用位运算
    a = a ^ b;
    b = a ^ b; // b = (a ^ b) ^ b -> a ^ (b ^ b) = a
    a = a ^ b; // a = (a ^ b) ^ a -> (a ^ a) ^ b = b
  }
}
